package com.example.myapplication.ui.home;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import com.bumptech.glide.Glide;
import com.example.myapplication.R;

import java.util.List;

public class ViewPagerAdapter extends PagerAdapter {
    private Context context;
    private List<Banner> banners;

    public ViewPagerAdapter(Context context, List<Banner> banners) {
        this.context = context;
        this.banners = banners;
    }

    @Override
    public int getCount() {
        return banners.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_banner, container, false);
        ImageView imageView = view.findViewById(R.id.bannerImage);
        TextView titleView = view.findViewById(R.id.bannerTitle);

        Banner banner = banners.get(position);

        // 使用Glide加载网络图片
        Glide.with(context)
                .load(banner.getImageUrl())
                .placeholder(R.drawable.placeholder_image)
                .error(R.drawable.error_image)
                .into(imageView);

        // 设置标题
        titleView.setText(banner.getTitle());

        // 设置点击事件 - 跳转到对应的课程详情
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到课程详情页，传递课程ID
                Intent intent = new Intent(context, CourseDetailActivity.class);
                intent.putExtra("courseId", banner.getCourseId());
                context.startActivity(intent);
            }
        });

        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }
}